<?php

/**
 * Cache Captcha Security Class
 * 
 * @project : Loobica Ads
 * @author  : Dino
 * @date    : 11 Jan 2014
 * 
 */
if (!defined('BASEPATH'))
  exit('No direct script access allowed');

class User_security {

  // Static vars
  private $ci;
  private $attempts = 5;
  private $timeout = 7200;
  // Dynamic vars
  private $try = 1;
  private $answer = null;
  private $key = null;
  private $captcha = array();
  private $validation = false;
  private $required = false;

  /**
   * Generate user key
   * 
   */
  public function __construct() {
    $this->ci = & get_instance();
    $this->key = md5($this->ci->input->ip_address());
  }

  /**
   * Run the captcha
   * 
   */
  public function run() {

    // Getting captcha cache
    $get_cache = $this->get();

    // Checking how may time user tried
    if ((!$this->required) && !empty($get_cache['try'])) {
      $this->try = (int) $this->try + $get_cache['try'];
    }

    // Checking answer
    if (!empty($get_cache['answer'])) {
      if ($this->ci->input->post('user_security_answer', true) == $get_cache['answer']) {
        $this->validation = true;
      }
    }

    // Enable captcha after maximum attempts
    if ($this->try > $this->attempts) {
      $this->required = true;
    }

    // Make new captcha
    if ($this->required) {
      $this->captcha = $this->generate();
    }

    // Set captcha
    $this->set();

    // Return security question
    return $this->captcha;
  }

  /**
   * Returns weather validation is success
   * 
   */
  public function validation() {
    return $this->validation;
  }

  /**
   * Force captcha enabled always
   * 
   */
  public function always() {
    $this->required = true;
    return $this;
  }

  /**
   * Clear cache array
   * 
   */
  public function clear() {
    return $this->ci->cache->delete($this->key);
  }

  /**
   * Get cache array
   * 
   */
  private function get() {
    return $this->ci->cache->get($this->key);
  }

  /**
   * Set cache array
   * 
   */
  private function set() {
    $cache_data = array('try' => $this->try, 'answer' => $this->answer);
    return $this->ci->cache->save($this->key, $cache_data, $this->timeout);
  }

  /**
   * Generate random question and its answer
   * 
   */
  private function generate() {
    $captcha = array();
    $captcha['question_one'] = rand(1, 99);
    $captcha['question_two'] = rand(1, 9);
    $captcha['question_ans'] = (int) $captcha['question_one'] + $captcha['question_two'];
    $this->answer = $captcha['question_ans'];
    return $captcha;
  }

}

?>